﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
using System.IO;

namespace Ebiz
{
    public class uploadHandler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            context.Response.Expires = -1;
            try{
                HttpPostedFile postedFile = context.Request.Files["Filedata"];
                string savepath = "";
                string tmpPath = "";
                tmpPath = System.Configuration.ConfigurationManager.AppSettings["FolderPath"];
                savepath = context.Server.MapPath("~/images/upload/");
                string tmpFileName = postedFile.FileName;
                string filename = renameIfExist(tmpFileName);
                //string filename = postedFile.FileName;

                if (!Directory.Exists(savepath)){
                    Directory.CreateDirectory(savepath);
                }

                postedFile.SaveAs(savepath + @"\" + filename);
                //context.Response.Write(tmpPath + "/" + filename);
                context.Response.Write(filename);
                context.Response.StatusCode = 200;

            }catch (Exception ex) {
                context.Response.Write("Error: " + ex.Message);
            }
        }

        private static string renameIfExist(string fileName) {
            string result = "";

            string[] tmpFile = fileName.Split('.');
            if (File.Exists(HttpContext.Current.Server.MapPath("~/images/upload/" + fileName))){
                Random rnd = new Random();
                int numExt = rnd.Next(1, 9999);
                string sExt = numExt.ToString().PadLeft(4, '0');
                result = tmpFile[0].ToString() + sExt + "." + tmpFile[1].ToString();
            }else{
                result = fileName;
            }
            return result;
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
